# -*- coding: cp866 -*-
import datetime
import time

TIME_FORMAT_MAGIC = '%d%m%Y_%H%M%S'

MS_MSGID_TO_CONTACTID = {
    '11':'1103',
    '13':'1103',
    '20':'1101',
    '22':'1101',
    '39':'6031',
    '26':'8011',
    '31':'8021',
    '32':'8031',
    '33':'8041',
    '34':'8051',
    '35':'8061',
    '36':'8071',
    '37':'8081',
    '38':'8091',
    '39':'8101',
    '40':'8111',
    '41':'8121',
    '45':'8131',
    '47':'8141',
    '48':'8151',
    '77':'8161',
    '84':'8171',
    '86':'8181',
    '87':'8191',
    '88':'8201',
    '94':'8211',
    '59':'8221',
    '60':'8231',
    '61':'8241',
    '62':'8251',
    '63':'8261',
    '64':'8271',
    '65':'8281',
    '66':'8291',
    '67':'8301',
    '68':'8311',
    '69':'8321',
    '70':'8331',
    '71':'8341',
    '72':'8351',
    '73':'8361',
    '74':'8371',
    '75':'8381',
    '76':'8391',
    '78':'8401',
    '79':'8411',
    '80':'8421',
    '90':'8431',
    '91':'8441',
    '92':'8451',
    '93':'8461',
    '96':'8471',
    '97':'8481',
    '98':'8491',
    '99':'8501',
    '100':'8511',
    '101':'8521',
    '102':'8531',
    '103':'8541',
    '104':'8551',
    '105':'8561',
    '107':'8571',
    '108':'8581',
    '116':'8591',
    '117':'8601',
    '118':'8611',
    '119':'8621',
    '126':'8631',
    '127':'8641'
}
MS_BOLID_TO_CONTACTID = {
    'ВЗЛОМКОРПУСА':'3831',
    'ВОССТ.КОРПУСА':'3833',
    'ПОЖ':'1101',
    'ПОЖАР':'1101',
    'СБРОСТРЕВОГИШС':'1103',
    'ВНИМАНИЕ':'1181',
    'ТРЕВОГА':'1231',
    'ТИХАЯТРЕВОГА':'1221',
    'ТРЕВОГАВХОДА':'1341',
    'ИЗМ.ДАТЫ':'6253',
    'ВЗЯТШС':'4003',
    'СНЯТШС':'4011',
    'ПРОГРАММИРОВАНИЕ':'6271',
    'СБРОСПРИБОРА':'3051',
    'ОБР':'3311',
    'КЗ':'3321',
    'АВПИТ':'3011',
    'ВОССТ':'3013',
    'ОБРЫВШС':'3311',
    'РАЗДЕЛВЗЯТ':'4023',
    'РАЗДЕЛСНЯТ':'4021',
    'КОРОТКОЕЗАМЫКАН':'3321',
    'ИДЕНТИФИКАЦИЯХО':'4221',
    'КЗВЫХОДА':'3201',
    'ОБРЫВВЫХОДА':'3201',
    'НЕИСПР.ТЕЛ.ЛИНИИ':'3501',
    'НЕИЗ.СОБЫТИЕ091':'3503',
    'ВЫКЛ.ПРИНТЕРА':'3361',
    'ВКЛ.ПРИНТЕРА':'3363',
    'ИЗМ.ВРЕМЕНИ':'6253'
}
MS_CONTACTID_TO_MSG = None
def loadCID():
    global MS_CONTACTID_TO_MSG
    if MS_CONTACTID_TO_MSG == None:
        f = open('contactid_messages.cfg', 'r')
        MS_CONTACTID_TO_MSG = {}
        for s in f.readlines():
            try:
                s = s.split('--')
                MS_CONTACTID_TO_MSG[s[0]] = s[1]
            except:
                continue
loadCID()

def eventType(cid, mode='l'):
    v = cid[6:7]
    if v == 'E': v = '1'
    if v == 'R': v = '3'
    if v == 'P': v = '6'

    if mode == 'l':     return {'1':'E', '3':'R', '6':'P'}.get(v, None)
    if mode == 'd':     return v
    if mode == 't':     return {'1':'Event of', '3':'Resore of', '6':'Previous of'}.get(v, None)
    return None
def eventCode(cid, mode='t'):
    global MS_CONTACTID_TO_MSG

    v = cid[7:10]
    if mode == 'd':     return v
    if mode == 't':     return MS_CONTACTID_TO_MSG.get(v, 'Unknown Contact ID Type %s' % (str(v)))
    return None

class Event:
    def __init__(self):
        self.eventId    = 0
        self.objectId   = 0
        self.eventReceiveTime   = datetime.datetime.fromtimestamp(time.time())
        self.eventGenerateTime  = self.eventReceiveTime

        self.isWrittenToPCNMySQL        = False
        self.isWrittenToPCNFB           = False
        self.isWrittenToCOMSecurithor   = False

        self.pgsmType       = 0

        self.contactIdOrig  = ''
        self.contactIdFull  = self.contactIdOrig
        self.contactIdType  = ''
        self.contactIdCode  = ''
        self.contactIdZona  = ''
        self.contactIdGroup = ''

        self.gpsLatitude    = 0.0
        self.gpsLongitude   = 0.0
        self.gpsSpeed       = 0.0

        self.photoContent   = None
        self.photoRef       = None

    def __cmp__(self, y):
        if y == None: return 1

        if self.eventGenerateTime > y.eventGenerateTime:    return 1
        if self.eventGenerateTime < y.eventGenerateTime:    return -1
        if self.eventId > y.eventId:    return 1
        if self.eventId < y.eventId:    return -1
        if self.pgsmType > y.pgsmType:  return 1
        if self.pgsmType < y.pgsmType:  return -1
        return 0

    def fromPhoto(self, rawEvent):
        if rawEvent.has_key('id'):          self.eventId    = rawEvent['id']
        if rawEvent.has_key('devid'):       self.objectId   = rawEvent['devid']
        self.eventGenerateTime  = datetime.datetime.strptime(rawEvent['date'], TIME_FORMAT_MAGIC)
        self.photoContent       = rawEvent['image']
        return True

    def fromPGSM(self, rawEvent):
        global MS_MSGID_TO_CONTACTID
        global TIME_FORMAT_MAGIC
        if rawEvent.has_key('id'):          self.eventId    = rawEvent['id']
        if rawEvent.has_key('devid'):       self.objectId   = rawEvent['devid']
        self.pgsmType           = rawEvent['type']
        self.contactIdType      = MS_MSGID_TO_CONTACTID.get(str(rawEvent['type']), '0001')
        self.eventGenerateTime  = datetime.datetime.strptime(rawEvent['datetime'], TIME_FORMAT_MAGIC)

        self.contactIdZona  = '099'
        self.contactIdGroup = '00'
        cidetype    = self.contactIdType[3]
        cidtype     = self.contactIdType[0:3]
        cidobj      = str(self.objectId)
        while len(cidobj) < 4: cidobj = '0' + cidobj
        self.contactIdFull = '18' + cidobj + cidetype + cidtype + self.contactIdGroup + self.contactIdZona + '0'
        self.contactIdOrig = self.contactIdFull
        return True

    def fromContactId(self, rawEvent):
        global TIME_FORMAT_MAGIC
        if rawEvent.has_key('eventid'):     self.eventid    = rawEvent['eventid']
        cid = rawEvent['value']
        self.contactIdOrig = cid
        self.objectId = cid[0:4]
        cidetype    = cid[6:7]
        cidtype     = cid[7:10]
        self.contactIdType  = '%s%s' % (cidtype, cidetype)
        self.contactIdGroup = cid[10:12]
        self.contactIdZona  = cid[12:15]
        self.contactIdFull = '18' + self.objectId + cidetype + cidtype + self.contactIdGroup + self.contactIdZona + '0'
        self.objectId = str(int(self.objectId))
        self.eventGenerateTime  = datetime.datetime.strptime(rawEvent['date'], TIME_FORMAT_MAGIC)

    def fromBolid(self, rawEvent):
        global TIME_FORMAT_MAGIC

        rawParsed   = str(rawEvent['type']).split('|')
        rawType     = rawParsed[2].replace(' ', '').decode('cp866').encode('u8')
        rawZone     = rawParsed[3].replace(' ', '')
        rawZone     = rawZone.split('/')
        if len(rawZone) == 2: self.contactIdZona = str(rawZone[1])
        if len(self.contactIdZona) < 3: self.contactIdZona = '0' + self.contactIdZona
        rawGroup    = rawParsed[4].replace(' ', '')
        if len(rawGroup) > 0: self.contactIdGroup = str(rawGroup)
        if len(self.contactIdGroup) < 2: self.contactIdGroup = '0' + self.contactIdGroup

        self.contactIdType = MS_BOLID_TO_CONTACTID.get(str(rawType), '0000')
        if self.contactIdType == '0000':
            raise Exception('unknown Bolid type %s' % (str(rawType)))
        self.eventGenerateTime  = datetime.datetime.strptime(rawEvent['datetime'], TIME_FORMAT_MAGIC)

    def fromGPSPoint(self, rawEvent):
        #we should transfer LAT and LON
        #LAT
        ddd = float(rawEvent['lat'])
        self.GPSLatitudeOrig = ddd
        dd = int(ddd)
        mm = int((ddd - dd)*60)
        ss = str(((ddd - dd)*60 - mm)*60)
        mm = str(mm)
        if (len(mm)) < 2:
            mm = '0%s' % (mm[0])
        dd = str(dd)
        self.GPSLatitude = dd[0:2] + mm[0:2] + '.' + ss.replace('.','')[0:5]
        #LON
        ddd = float(rawEvent['lon'])
        self.GPSLongitudeOrig = ddd
        dd = int(ddd)
        mm = int((ddd - dd)*60)
        ss = str(((ddd - dd)*60 - mm)*60)
        mm = str(mm)
        if (len(mm)) < 2:
            mm = '0%s' % (mm[0])
        dd = str(dd)
        self.GPSLongitude = dd[0:2] + mm[0:2] + '.' + ss.replace('.','')[0:5]
        self.GPSSpeed = rawEvent['speed']
        self.eventGenerateTime = datetime.datetime.strptime(rawEvent['date'], TIME_FORMAT_MAGIC)
        if rawEvent.has_key('eventid'):     self.eventid    = rawEvent['eventid']
        if rawEvent.has_key('devid'):       self.objectId   = rawEvent['devid']
